import functools
import json

from flask import (
    Blueprint, flash, g, redirect, render_template, request, session, url_for,Response,abort,jsonify
)
from werkzeug.security import check_password_hash, generate_password_hash

from flaskr.db import get_db

from flask_cors import *

bp = Blueprint('nucleic-acid', __name__, url_prefix='/')

cors=CORS(bp,supports_credentials=True)

@bp.route('/nucleic-acid-test', methods=['GET', 'POST'])
def nucleic_acid_test():
    if request.method == 'POST':
        data = request.get_data()    
        data = json.loads(data.decode("utf-8"))
        if(session.get('permission') != 'User'):
            abort(403)
        db = get_db()
        try:
            db.execute(
                "UPDATE Medical_point set nucleic_acid = nucleic_acid -1 where id = ?",
                (session.get('id'),),
            )
            db.execute(
                "INSERT INTO Nucleic_acid_record (user_id, medical_point_id, status) VALUES (?, ?, ?)",
                (session.get('id'), data['medical_point_id'], 3,),
            )
            db.commit()
        except db.IntegrityError:
            abort(500)
        else:
            return "success"
            
    elif request.method == 'GET':
        if(session.get('permission') != 'User'):
            abort(403)
        username = session.get('id')
        db = get_db()
        test_records = db.execute(
            'SELECT time,status,medical_point_id FROM Nucleic_acid_record WHERE user_id = ?', (username,)
        ).fetchall()
        record_list = []
        for record in test_records:
            record_list.append({'medical_point_id':record['medical_point_id'],'time':record['time'],'result':record['status']})
        return jsonify({'record_list':record_list})
    abort(405)  #method not allowed

@bp.route('/nucleic-acid-add', methods=['POST'])
def nucleic_acid_add():
    if request.method == 'POST':
        data = request.get_data()    
        data = json.loads(data.decode("utf-8"))
        if(session.get('permission') != 'Medical_point'):
            abort(403)
        db = get_db()
        try:
            db.execute(
                "UPDATE Medical_point set nucleic_acid = nucleic_acid + ? where id = ?",
                (data['number'],session.get('id'),),
            )
            db.commit()
        except db.IntegrityError:
            abort(500)
        else:
            return "success"

@bp.route('/nucleic-acid-record', methods=['GET','POST'])
def nucleic_acid_record():
    if request.method == 'POST':
        data = request.get_data()    
        data = json.loads(data.decode("utf-8"))
        if(session.get('permission') != 'Medical_point'):
            abort(403)
        db = get_db()
        try:
            db.execute(
                "UPDATE Nucleic_acid_record set status = ? where id = ?",
                (data['result'],data['record-ID'],),
            )
            db.commit()
        except db.IntegrityError:
            abort(500)
        return "success"
    elif request.method == 'GET':
        if(session.get('permission') == 'Medical_point'):
            db = get_db()
            test_records = db.execute(
                'SELECT Nucleic_acid_record.id,username,time,Nucleic_acid_record.status FROM Nucleic_acid_record join User WHERE medical_point_id = ? and (Nucleic_acid_record.status = 3 or Nucleic_acid_record.status = 2) and user_id = User.id', (session.get('id'),)
            ).fetchall()
            record_list = []
            for record in test_records:
                record_list.append({'id':record['id'], 'username':record['username'],'time':record['time'],'result':record['status']})
            return jsonify({'record_list':record_list})
        abort(403)
        